package com.spingbootes.kizuki.es;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;


@Slf4j
@AllArgsConstructor
public class ESManger<T> {

    private ExecuteUtil executeUtil;

    public List handler(Map<String, ExecuteUtil.Caller> map){
        if (map.keySet().size() >= ESConfig.AYSNC_NEED_INDEX) {
            return doAysncHandler(map);
        } else {
            return doHandler(map);
        }
    }

    public List doAysncHandler(Map<String, ExecuteUtil.Caller> map){
        long beginTime = System.currentTimeMillis();
        Set<String> indexs = map.keySet();
        List<Future<T>> futures = new ArrayList<>(indexs.size());
        indexs.forEach(index -> {
            try {
                Future<T> future = executeUtil.asyncExecute(map.get(index));
                futures.add(future);
            } catch (Exception e) {
                log.info("查询es异常, index:{}", index);
            }
        });

        List result = new ArrayList();
        futures.forEach(future -> {
            try {
                T t = future.get();
                if (t instanceof List) {
                    result.addAll((List)t);
                } else {
                    result.add(t);
                }
            } catch (InterruptedException | ExecutionException e) {
                log.info("查询es异常, {}", e);
            }
        });
        log.info("异步操作总耗时, {}ms", System.currentTimeMillis() - beginTime);
        return result;
    }

    public List doHandler(Map<String, ExecuteUtil.Caller> map){
        long beginTime = System.currentTimeMillis();
        Set<String> indexs = map.keySet();

        List result = new ArrayList();
        indexs.forEach(index -> {
            T t = (T) executeUtil.execute(map.get(index));
            if (t instanceof List) {
                result.addAll((List)t);
            } else {
                result.add(t);
            }
        });
        log.info("同步操作总耗时, {}ms", System.currentTimeMillis() - beginTime);
        return result;
    }

}
